package com.maxuxu.scihome.controller.document;

import com.maxuxu.scihome.pojo.Document;
import com.maxuxu.scihome.service.DocumentService;
import com.maxuxu.scihome.utils.UploadFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @className: NoticeDownloadController
 * @author: Maxuxu
 * @date: 2022/7/1 20:23
 * @description: 文档的下载类
 */

@RestController
@Slf4j
public class DocumentUploadController {
    @Autowired
    DocumentService documentService;
    @Autowired
    Document document;

    @Autowired
    UploadFile uploadFile;

    /**
     * 上传文档功能
     * @param title
     * @param remark
     * @param file
     * @param session
     * @return
     * @throws IOException
     */

    @PostMapping("/document/upload")
    public Document uploadPost(@RequestParam("title") String title,
                                          @RequestParam("remark") String remark,
                                          @RequestParam("file") MultipartFile[] file,
                                          HttpSession session) throws IOException {
        String originalFilename = uploadFile.upload(file);
        log.error("上传的用户名为："+originalFilename);
        document.setFilename(originalFilename);
        document.setRemark(remark);
        document.setTitle(title);
        document.setCreateDate(new Date());
        documentService.insertDocu(document);
        return document;
    }

    /**
     * 更新文档功能
     * @param remark
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/document/update")
    public Document updateDocu(@RequestParam("title") String title,
                               @RequestParam("remark")  String remark,
                               @RequestParam("file")  MultipartFile[] file,
                               @RequestParam("oldtitle")  String oldtitle
                               ) throws IOException {
        log.error("文档的原标题{}", oldtitle);
        String filename = null;
        if (file != null) {
            filename = uploadFile.upload(file);
        }
        document.setFilename(filename);
        document.setRemark(remark);
        document.setTitle(title);
        document.setCreateDate(new Date());

        documentService.updateDocument(oldtitle,document);
        return document;
    }
}
